package cn.rknn.iot.engine.mqtt;

import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class MqttService {

    @Resource
    private MqttClient mqttClient;

    @Resource
    private MqttMessageListener mqttMessageListener;

    private void publishMessage(String topic, String payload) {
        MqttMessage message = new MqttMessage(payload.getBytes());
        try {
            mqttClient.publish(topic, message);
            log.info("发送mqtt消息成功:{}", payload);
        } catch (MqttException e) {
            log.error("发送mqtt消息失败", e);
        }
    }


    public void subscribeToTopics(String topic) {
        try {
            mqttClient.subscribe(topic, mqttMessageListener);
            log.info("订阅mqtt主题成功:{}", topic);
        } catch (MqttException e) {
            log.error("订阅mqtt主题失败", e);
        }
    }
}